package com.hn.project.common.service.impl;

import com.hn.common.utils.sql.SqlUtil;
import com.hn.project.common.domain.City;
import com.hn.project.common.domain.District;
import com.hn.project.common.domain.Province;
import com.hn.project.common.mapper.CityMapper;
import com.hn.project.common.mapper.DistrictMapper;
import com.hn.project.common.mapper.ProvinceMapper;
import com.hn.project.common.service.ProvinceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述:
 *
 * @date 2019-12-24 16:27
 */
@Service
public class ProvinceServiceImpl implements ProvinceService {

    private static Map<String, List<Province>> map = new HashMap();

    @Autowired
    private ProvinceMapper provinceMapper;

    @Autowired
    private CityMapper cityMapper;

    @Autowired
    private DistrictMapper districtMapper;

    @Override
    public List<Province> listProvince() {
        List<Province> provinces = map.get("provinceAndCity");
        if (provinces == null || provinces.isEmpty()) {
            provinces = provinceMapper.selectAll();
            for (Province province : provinces) {
                Example example = SqlUtil.newExample(City.class);
                example.createCriteria().andEqualTo("provinceId", province.getProvinceId());
                List<City> cities = cityMapper.selectByExample(example);
                province.setCityList(cities);
            }
            map.put("provinceAndCity", provinces);
        }
        return provinces;
    }

    @Override
    public List<Province> listProvinceCity() {
        List<Province> provinces = map.get("provinceAndCityAndDistrict");
        if (provinces == null || provinces.isEmpty()) {
            provinces = listProvince();
            for (Province province : provinces) {
                List<City> cityList = province.getCityList();
                for (City city : cityList) {
                    Example example = SqlUtil.newExample(District.class);
                    example.createCriteria().andEqualTo("cityId", city.getCityId());
                    List<District> districts = districtMapper.selectByExample(example);
                    city.setDistricts(districts);
                }
            }
            map.put("provinceAndCityAndDistrict", provinces);
        }
        return provinces;
    }
}
